document.addEventListener('DOMContentLoaded', function () {
    let viewCaseListeners = [];
    let approveListeners = [];
    let rejectListeners = [];
    let currentModal = null;

    function getQueryParameter(datatype) {
        const urlParams = new URLSearchParams(window.location.search);
        return urlParams.get(datatype);
    }

    doctorName = getQueryParameter('name')
    doctorInfo = {
        doctor_name: doctorName
    }
    console.log(doctorInfo)

    // 模拟数据源，实际应用中应该是从服务器请求数据
    const data = [
        { caseID: '1', patient: 'bbb', patientID: '112233445566', bedId: 'YK.101', avg_day: '5天' },
        { caseID: '2', patient: 'bbb', patientID: '112233125566', bedId: 'YK.101', avg_day: '5天' },
        { caseID: '3', patient: 'bbb', patientID: '113232125566', bedId: 'YK.101', avg_day: '5天' },
        // 其他数据项...
    ];

    const tableBody = document.querySelector('.sectionForm > tbody');
    if (!tableBody) {
        // 如果不存在tbody，则创建一个新的tbody
        const tbody = document.createElement('tbody');
        document.querySelector('.sectionForm').appendChild(tbody);
    } else {
        tableBody.innerHTML = ''; // 清空已有的tbody内容
    }

    data.forEach(item => {
        const row = document.createElement('tr');
        row.classList.add('mt-33');

        //获取当前病例id，用于后续区分
        current_id = item.caseID
       

        Object.values(item).forEach(value => {
            const cell = document.createElement('td');
            cell.classList.add('font', 'text_3');
            cell.textContent = value;
            row.appendChild(cell);
        });

        // 创建一个单元格放查看病例按钮
        const viewCaseCell = document.createElement('td');
        viewCaseCell.classList.add('font', 'text_3', 'shrink-0', 'ml-121');


        // 创建一个单元格放同意和拒绝按钮
        const actionCell = document.createElement('td');
        actionCell.classList.add('font', 'text_3', 'shrink-0', 'ml-121');

        const viewCaseButton = createButton(current_id + '_case', '查看病例');
        const approveButton = createButton(current_id + '_approve', '同意');
        const rejectButton = createButton(current_id + '_reject', '拒绝', true);

        viewCaseCell.appendChild(viewCaseButton);
        actionCell.appendChild(approveButton);
        actionCell.appendChild(rejectButton);

        row.appendChild(viewCaseCell);
        row.appendChild(actionCell);

        tableBody.appendChild(row);

        // 绑定事件监听器
        viewCaseButton.addEventListener('click', function () {
            case_id = (viewCaseButton.id).split("_")[0];

            case_info = {
                caseID : case_id
            }
            console.log(case_info)

            //获取病人信息
            //json = 

            if (!currentModal) {
                display_patient_information(json);
            }
        });

        approveButton.addEventListener('click', function () {
            case_id = (viewCaseButton.id).split("_")[0];
            showApprovalDialog('同意', case_id);
        });
        rejectButton.addEventListener('click', function () {
            case_id = (viewCaseButton.id).split("_")[0];
            showApprovalDialog('拒绝', case_id);
        });

        // Store the listeners for later removal
        viewCaseListeners.push(viewCaseButton);
        approveListeners.push(approveButton);
        rejectListeners.push(rejectButton);
    });




    // Function to remove old event listeners when DOMContentLoaded fires again
    function removeOldEventListeners() {
        viewCaseListeners.forEach(button => {
            button.removeEventListener('click', display_patient_information);
        });
        approveListeners.forEach(button => {
            button.removeEventListener('click', showApprovalDialog);
        });
        rejectListeners.forEach(button => {
            button.removeEventListener('click', showApprovalDialog);
        });
    }

    // Remove old event listeners before adding new ones
    removeOldEventListeners();
});

// 显示/隐藏模态框
function showApprovalDialog(action, case_id) {
    var approvalContainer = document.createElement('div');
    approvalContainer.id = action == '同意' ? 'approve' : 'reject';
    approvalContainer.className = 'modal-container';
    approvalContainer.style.textAlign = 'left';

    // 创建modal-content div  
    var modalContent = document.createElement('div');
    modalContent.className = 'modal-content';
    modalContent.style.display = 'block';

    var approvalHead = document.createElement('h2');
    approvalHead.id = 'patient-head';
    approvalHead.style.textAlign = 'center';
    approvalHead.textContent = '提示信息';

    var action_message = modal_div_creator(action, 'error_information', `您确定要${action}吗？`);
    var approve = modal_button_creator('approve-button', '确认')
    var cancel = modal_button_creator('cancel-button', '取消')

    modalContent.appendChild(approvalHead)
    modalContent.appendChild(action_message)
    modalContent.appendChild(approve)
    modalContent.appendChild(cancel)

    // 给确定按钮添加点击事件监听器  
    approve.addEventListener('click', function () {
        if (approvalContainer.id == 'approve') {
            requestLine = document.getElementById(case_id + '_approve').parentNode.parentNode;
            if (requestLine.parentNode)
                requestLine.parentNode.removeChild(requestLine)

            //同意请求相关代码
            request_info = {
                caseID : case_id
            }
            console.log(request_info)

            //result = 
            //display_alert_information(result.message)

        }
        else {
            requestLine = document.getElementById(case_id + '_reject').parentNode.parentNode;
            if (requestLine.parentNode)
                requestLine.parentNode.removeChild(requestLine)
            
            //拒绝请求相关代码
            request_info = {
                caseID : case_id
            }
            console.log(request_info)

            //result = 
            //display_alert_information(result.message)
        }
        if (approvalContainer.parentNode) {
            approvalContainer.parentNode.removeChild(approvalContainer);
        }

    });


    // 给取消按钮添加点击事件监听器  
    cancel.addEventListener('click', function () {
        if (approvalContainer.parentNode) {
            approvalContainer.parentNode.removeChild(approvalContainer);
        }
    });

    approvalContainer.appendChild(modalContent);

    document.body.appendChild(approvalContainer);
}


// 创建按钮并返回
function createButton(id, text, isSecondary = false) {
    const button = document.createElement('button');
    button.id = id;
    button.className = `justify-start items-center ${isSecondary ? 'text-wrapper_2' : 'text-wrapper'}`;
    const span = document.createElement('span');
    span.className = 'font_3 text_3';
    span.textContent = text;
    button.appendChild(span);

    return button;
}


function display_patient_information(data) {
    var patientContainer = document.createElement('div');
    patientContainer.id = 'patient-container';
    patientContainer.className = 'modal-container';
    patientContainer.style.textAlign = 'left';

    // 创建modal-content div  
    var modalContent = document.createElement('div');
    modalContent.className = 'modal-content';
    modalContent.style.display = 'block';

    var patientHead = document.createElement('h2');
    patientHead.id = 'patient-head';
    patientHead.style.textAlign = 'center';
    patientHead.textContent = '病人信息';

    // 修改模式框内容
    var chargerName = modal_div_creator('charger-name', 'bed_card_information', '病床管理者姓名: ' + data.charge_doctor_id);
    var chargerID = modal_div_creator('charger-id', 'bed_card_information', '病床管理者ID: ' + data.charge_doctor_name);
    var patientName = modal_div_creator('patient-name', 'bed_card_information', '病人姓名: ' + data.patient_info.patient_name);
    var patientID = modal_div_creator('patient-id', 'bed_card_information', '病人ID: ' + data.patient_info.patient_id);
    var patientGender = modal_div_creator('patient-gender', 'bed_card_information', '病人性别: ' + data.patient_info.gender);
    var patientAge = modal_div_creator('patient-age', 'bed_card_information', '病人年龄: ' + data.patient_info.age);
    var doctorName = modal_div_creator('doctor-name', 'bed_card_information', '医生姓名: ' + data.patient_info.doctor_name);
    var doctorID = modal_div_creator('doctor-id', 'bed_card_information', '医生ID: ' + data.patient_info.doctor_id);
    var description = modal_div_creator('description', 'bed_card_information', '病例描述: ' + data.patient_info.description);
    var cancel = modal_button_creator('cancel-button', '取消')

    modalContent.appendChild(patientHead);
    modalContent.appendChild(chargerName);
    modalContent.appendChild(chargerID);
    modalContent.appendChild(patientName);
    modalContent.appendChild(patientID);
    modalContent.appendChild(patientGender);
    modalContent.appendChild(patientAge);
    modalContent.appendChild(doctorName);
    modalContent.appendChild(doctorID);
    modalContent.appendChild(doctorName);
    modalContent.appendChild(description);
    modalContent.appendChild(cancel)

    // 给取消按钮添加点击事件监听器  
    cancel.addEventListener('click', function () {
        // 从 DOM 中移除 patientContainer  
        if (patientContainer.parentNode) {
            patientContainer.parentNode.removeChild(patientContainer);
        }
    });

    patientContainer.appendChild(modalContent);

    document.body.appendChild(patientContainer);
}

